package logic

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/Baidu-AIP/golang-sdk/aip/censor"
	"log"
	"server/models"
	"server/proto"
	"strconv"
)

// todo: 商品添加
func (s *ServerRpc) EsAdd(ctx context.Context, in *proto.EsAddReq) (*proto.EsAddRes, error) {
	//todo: 百度智能云   敏感词过滤
	client := censor.NewCloudClient("ak", "sk")
	result := client.TextCensor(in.GoodsName)
	var rr map[string]interface{}
	json.Unmarshal([]byte(result), &rr)
	if rr["conclusion"] == "不合规" {
		log.Println("文本不合规")
		return &proto.EsAddRes{}, errors.New("文本不合规")
	}

	Inquire := strconv.Itoa(int(in.GoodsInquire))
	Status, _ := strconv.Atoi(in.GoodsStatus)
	//todo: 添加数据库
	goods, err := models.CreateGoods(models.Goods{
		GoodsName:    in.GoodsName,
		GoodsPrice:   in.GoodsPrice,
		GoodsInquire: Inquire,
		GoodsAddress: in.GoodsAddress,
		GoodsImg:     in.GoodsImg,
		GoodsStatus:  Status,
	})
	if err != nil {
		log.Println("mysql添加失败")
		return &proto.EsAddRes{}, err
	}
	//todo：添加es
	err = models.EsAdd(in.Index, goods)
	if err != nil {
		log.Println("es添加失败")
		return &proto.EsAddRes{}, err
	}
	return &proto.EsAddRes{}, nil
}
